﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotonJXC.Entity;
using BotonJXC.Util;
using BotonJXC.BLL;

namespace BotonJXC.Forms
{
    public partial class PickingMainForm : BaseMdiForm
    {
        private Pickings pickings = null;
        private int pageNo = 0;

        public PickingMainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PickingOrderForm_Load(object sender, EventArgs e)
        {
            initFormData();
        }

        /// <summary>
        /// 增加按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonaddproduct_Click(object sender, EventArgs e)
        {
            BindingList<PickingsProducts> staticlist = (BindingList<PickingsProducts>)PickinguserDataGridViewProduct.DataSource;
            PickingsProducts _product = new PickingsProducts();
            staticlist.Add(_product);
            PickinguserDataGridViewProduct.Refresh();
        }

        /// <summary>
        /// 删除按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtondelproduct_Click(object sender, EventArgs e)
        {
            if (PickinguserDataGridViewProduct.CurrentRow != null)
            {
                PickinguserDataGridViewProduct.Rows.Remove(PickinguserDataGridViewProduct.CurrentRow);
                //notifyandrealQuantityCount();
                PickinguserDataGridViewProduct.Refresh();
            }
        }

        /// <summary>
        /// 初始化窗体数据
        /// </summary>
        public void initFormData()
        {
            initComboBoxDate();
            if (pickings != null)
            {
                PickingSntb.Text = pickings.PickingSn;//单据编号
                SalesmanText.Text = "业务员：" + pickings.Salesman;//业务员
                if (pickings.OutStocks !=null)
                    OutStockstb.Text = pickings.OutStocks.OutSn;//相关单号
                PrintTimeText.Text = "打印次数：" + pickings.PrintTime;//打印次数
                OutWarehousecb.SelectedValue = pickings.OutWarehouse.WarehouseId;//出库库存地
                OutWarehousetb.Text = Utils.ToString(pickings.OutWarehouse.WarehouseId);

                InWarehousecb.SelectedValue = pickings.InWarehouse.WarehouseId;//入库库存地
                InWarehousetb.Text = Utils.ToString(pickings.InWarehouse.WarehouseId);

                OutBillTypecb.SelectedValue = Utils.ToInt(pickings.OutBillType,0);//相关单据类型

                AccountText.Text = "制单人：" + pickings.Account.Username;//制单人
                CreateTimeText.Text = "制单日期：" + string.Format("{0:yyyy/MM/dd HH:mm:ss}", pickings.CreateTime);//创建时间

                Remarktb.Text = pickings.Remark;//通知备注

                //货品集合
                BindingList<PickingsProducts> list = new BindingList<PickingsProducts>(pickings.PickingsProductsList);
                PickinguserDataGridViewProduct.DataSource = list;
                PickinguserDataGridViewProduct.Refresh();
            }

        }

        /// <summary>
        /// combobox数据加载
        /// </summary>
        public void initComboBoxDate()
        {
            //初始化配送出库库存地数据
            Warehouse outw = new Warehouse();
            IList<Warehouse> slist = new WarehouseBLL().FindAll();
            Warehouse wh = new Warehouse();
            wh.WarehouseId = 0;
            wh.Name = "请选择";
            slist.Insert(0, wh);
            OutWarehousecb.DataSource = slist;
            OutWarehousecb.DisplayMember = "Name";
            OutWarehousecb.ValueMember = "WarehouseId";

            //初始化配送入库库存地数据
            Warehouse inw = new Warehouse();
            IList<Warehouse> inlist = new WarehouseBLL().FindAll();
            Warehouse inwh = new Warehouse();
            inwh.WarehouseId = 0;
            inwh.Name = "请选择";
            inlist.Insert(0, inwh);
            InWarehousecb.DataSource = inlist;
            InWarehousecb.DisplayMember = "Name";
            InWarehousecb.ValueMember = "WarehouseId";
            

            //相关单据类型数据
            IList<ComboBoxItem> cbilist = new List<ComboBoxItem>();
            cbilist.Insert(0, new ComboBoxItem(0,"请选择"));
            cbilist.Insert(1, new ComboBoxItem(1, "分店配送出库"));
            cbilist.Insert(2, new ComboBoxItem(2, "分店报损出库"));
            cbilist.Insert(1, new ComboBoxItem(3, "配送中心调拨单"));
            cbilist.Insert(2, new ComboBoxItem(4, "配送中心配送出库"));
            
            OutBillTypecb.DataSource = cbilist;
            OutBillTypecb.DisplayMember = "Text";
            OutBillTypecb.ValueMember = "Value";

        }

         /// <summary>
        /// 重置窗体数据
        /// </summary>
        public void resetFormData()
        {
            pickings = null;
            PickingSntb.Text = "";//单据编号
            SalesmanText.Text = "业务员：";//业务员
            OutStockstb.Text = "";//相关单号
            PrintTimeText.Text = "打印次数：";//打印次数
            OutWarehousecb.SelectedValue = 0;//出库库存地
            OutWarehousetb.Text = "";

            InWarehousecb.SelectedValue = 0;//入库库存地
            InWarehousetb.Text = "";

            OutBillTypecb.SelectedValue = 0;//相关单据类型

            AccountText.Text = "制单人：";//制单人
            CreateTimeText.Text = "制单日期：";//创建时间

            Remarktb.Text = "";//通知备注

            //货品集合
            BindingList<PickingsProducts> list = new BindingList<PickingsProducts>();
            PickinguserDataGridViewProduct.DataSource = list;
            PickinguserDataGridViewProduct.Refresh();
        }

        /// <summary>
        ///  新建单据按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonaddorders_Click(object sender, EventArgs e)
        {
            resetFormData();
        }

         /// <summary>
        /// 封装拣货单信息
        /// </summary>
        public void packagingPicking(string _type)
        {
            if ("update".Equals(_type))
            {
                pickings.Salesman = LoginForm.Account.Username;//业务员
            }
            if ("add".Equals(_type))
            {
                pickings.PrintTime = 0;//打印次数
                pickings.Account = LoginForm.Account;//创建人
                pickings.CreateTime = DateTime.Now;//创建时间
            }
            

            //pickings.OutStocks = null;//相关单号
            pickings.OutBillType = ((ComboBoxItem)OutBillTypecb.SelectedItem).Value.ToString();//相关单据类型

            pickings.OutWarehouse = (Warehouse)OutWarehousecb.SelectedItem;//出库库存地
            pickings.InWarehouse = (Warehouse)InWarehousecb.SelectedItem;//入库库存地

            pickings.Remark = Remarktb.Text;//备注
        
        }

        /// <summary>
        /// 保存拣货单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonsaveproduct_Click(object sender, EventArgs e)
        {
            bool flag = false;
            if (pickings != null)
            {
                flag = save_pickingsOrders("update");
            }
            else
            {
                flag = save_pickingsOrders("add");
            }
            if (flag)
            {
                MessageBox.Show("保存成功");
                initFormData();
            }
        }

        /// <summary>
        /// 保存退货单
        /// </summary>
        /// <param name="_type"></param>
        /// <returns></returns>
        public bool save_pickingsOrders(string _type)
        {

            if ("add".Equals(_type))
            {
                string ordersn = new BillSNGenerator().GeneratorBillSn(BillType.Pickings, BillSource.DistributionCenter, LoginForm.Store);
                pickings = new Pickings();
                pickings.PickingSn = ordersn;
                packagingPicking(_type);
                return new PickingsBLL().SavePickings(pickings);
            }
            else
            {
                packagingPicking(_type);
                return new PickingsBLL().updatePickings(pickings);
            }
        }

        /// <summary>
        /// 查找数据
        /// </summary>
        /// <param name="start"></param>
        public void loadData(int start)
        {
            PageModel<Pickings> pageModellist = new PickingsBLL().FindPage(null,start,1);
            int pageCount = pageModellist.PageCount;//总页数
            pageNo = start;//当前页数
            if (pageNo == 0)
                lastPageButton.Enabled = false;
            else
                lastPageButton.Enabled = true;
            if ((pageNo + 1) == pageCount)
                nextPageButton.Enabled = false;
            else
                nextPageButton.Enabled = true;

            if (pageModellist.Results.Count > 0)
            {
                pickings = pageModellist.Results[0];
                initFormData();
            }
        }

        /// <summary>
        /// 单据查找
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            loadData(0);
        }

        /// <summary>
        /// 下一张单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nextPageButton_Click(object sender, EventArgs e)
        {
            loadData(pageNo+1);
        }

        /// <summary>
        /// 上一张单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lastPageButton_Click(object sender, EventArgs e)
        {
            loadData(pageNo - 1);
        }

        /// <summary>
        /// 单元格完成编辑事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PickinguserDataGridViewProduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "ProductCode")
            {
                string productCode = Utils.ToString(PickinguserDataGridViewProduct.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                if (productCode != null && !"".Equals(productCode))
                {
                    Product product = new ProductBLL().GetProductByCode(productCode);
                    if (product != null)
                    {
                        //货品条码
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["Barcode"].Value = product.Barcode;
                        //货品名称
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["ProductName"].Value = product.ProductName;
                        //货位号
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["CargoSpace"].Value = product.CargoSpace;
                        //类别
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["productType"].Value = product.Type;
                        //单位
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["DefUnit"].Value = product.DefUnit==null?"":product.DefUnit.UnitName;
                        //货品
                        PickinguserDataGridViewProduct.Rows[PickinguserDataGridViewProduct.CurrentRow.Index].Cells["Product"].Value = product;
                    }
                }
            }
        }

        /// <summary>
        /// 入库库存地选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InWarehousecb_SelectedIndexChanged(object sender, EventArgs e)
        {
            InWarehousetb.Text = ((Warehouse)InWarehousecb.SelectedItem).WarehouseId.ToString();
        }
        /// <summary>
        /// 出库库存地选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutWarehousecb_SelectedIndexChanged(object sender, EventArgs e)
        {
            OutWarehousetb.Text = ((Warehouse)OutWarehousecb.SelectedItem).WarehouseId.ToString();
        }

        /// <summary>
        /// 单元格格式化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PickinguserDataGridViewProduct_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            PickingsProducts p = PickinguserDataGridViewProduct.Rows[e.RowIndex].DataBoundItem as PickingsProducts;
            if (p != null && p.Product != null)
            {
                if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "Barcode")
                {
                    e.Value = p.Product.Barcode;
                }
                else if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "ProductCode")
                {
                    e.Value = p.Product.ProductCode;
                }
                else if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "ProductName")
                {
                    e.Value = p.Product.ProductName;
                }
                else if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "DefUnit")
                {
                    if (p.Product.DefUnit != null)
                        e.Value = p.Product.DefUnit.UnitName;
                }
                else if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "CargoSpace")
                {
                    e.Value = p.Product.CargoSpace;
                }
                else if (PickinguserDataGridViewProduct.Columns[e.ColumnIndex].Name == "productType")
                {
                    if (p.Product.Type != null)
                        e.Value = p.Product.Type.TypeName;
                }
            }
        }
    }
}
